<?php
namespace app\common\controller;

use EasyWeChat\OfficialAccount\Application;
use think\facade\Cache;
use think\facade\Config;

trait WxAccessToken
{
    protected static ?Application $wechat = null;

    public function __construct ()
    {
        $pay = Config::get("easy_wechat");
        if (self::$wechat === null) {
            self::$wechat = new Application($pay);
        }
    }

    /**
     * 获取access_token
     * @return string
     */
    public static function getAccessToken (): string
    {
        $token = Cache::get('wechat_access_token');
        if (!$token) {
            self::refreshToken();
            $token = Cache::get('wechat_access_token');
        }
        return $token;
    }

    /**
     * 刷新token
     * @return void
     */
    protected static function refreshToken (): void
    {
        if (self::$wechat === null) {
            $pay = Config::get("easy_wechat");
            self::$wechat = new Application($pay);
        }
        $token = self::$wechat->getAccessToken()->getToken();
        Cache::set('wechat_access_token', $token, 3600 * 2 - 10);
    }
}